package com.me.launcher.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.me.launcher.R;
import com.me.launcher.adapter.BottomAdapter;
import com.me.launcher.adapter.GridViewAdapter;
import com.me.launcher.adapter.WorkSpacePagerAdapter;
import com.me.launcher.bean.AppBean;
import com.me.launcher.bean.AppEvent;
import com.me.launcher.bean.ShortCutEvent;
import com.me.launcher.custom.CantScrollViewPager;
import com.me.launcher.custom.GragGridBottomView;
import com.me.launcher.custom.GragGridView;
import com.me.launcher.db.DBUtil;
import com.me.launcher.db.SharedPreferencesUtil;
import com.me.launcher.inter.DragStatus;
import com.me.launcher.tools.AnimUtil;
import com.me.launcher.tools.LogUtil;
import com.me.launcher.tools.ScreenUtils;
import com.me.launcher.tools.Tools;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author hejiangwei
 * @date 2018/3/30
 */
public class WorkSpaceFragment extends Fragment implements GragGridView.OnDragListener, GridViewAdapter.SetLastAppListener, BottomAdapter.SetChangeAppListener {

    private static final String TAG = "WorkSpaceFragment";
    public static List<GridViewAdapter> mViewAdapters = new ArrayList<>();
    public static int miPageIndex;


    /**
     * 标识着是否是拖拽app滑动切换屏幕
     */
    public static boolean mbToNext = false;
    public static int TopY, BottomY;
    public static int miLinesNum, miScreenNum;
    public static int iconSize, iconSpace, appHeight;
    private static Context mContext;
    int miInsertIndex = 0;
    private boolean isInDelete = false, isInInfo = false, mbIsToNext;
    private WorkSpacePagerAdapter myPagerAdapter;
    private OnDragListener mListener;
    private RelativeLayout mrlContent;
    private List<List<AppBean>> mShowApps = new ArrayList<>();
    private List<AppBean> mbotoms = new ArrayList<>();
    private List<AppBean> mappsAll = new ArrayList<>();
    private CantScrollViewPager mViewPager;
    private ArrayList<GragGridView> mViews = new ArrayList<>();
    private AppBean mDragBean;
    /**
     * 工作区左右滑动的点
     */
    private LinearLayout mllIndexs;
    /**
     * 底部热键位置
     */
    private GragGridBottomView mGridViewBottom;
    private BottomAdapter mAdapterBottom;
    /**
     * 点的实例集合
     */
    private ImageView[] mDianImages;
    private RelativeLayout mrlDelete;
    /**
     * 长按图标显示的卸载与信息按钮
     */
    private TextView mtvDeleteBtn, mtvAppInfo;
    private String mStrDragPkgName;

    public WorkSpaceFragment() {
        // Required empty public constructor
    }

    public static WorkSpaceFragment newInstance() {
        WorkSpaceFragment fragment = new WorkSpaceFragment();
        Bundle args = new Bundle();
//        args.putString(ARG_PARAM1, param1);
//        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public static void setShortCut(Intent intent) {


//        ComponentName componentName = intent.getComponent() ;
        Log.i(TAG, "ComponentName Info ----> " + intent.getStringExtra(Intent.EXTRA_SHORTCUT_INTENT));
        Log.i(TAG, "ComponentName Info ----> " +
                ((Intent) intent.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT)).getParcelableExtra("_VA_|_intent_"));


//        try
//        {
        //获取资源图片
//            ActivityInfo activityInfo = mContext.getPackageManager().getActivityInfo(componentName, 0);
//            CharSequence applabel = activityInfo.loadLabel(mContext.getPackageManager()) ;
//            Drawable appIcon = activityInfo.loadIcon(mContext.getPackageManager()) ;

        //创建一个View对象
//            View view = makeViewForShortcut(applabel , appIcon) ;
//            //为该快捷方式的View设置onClick监听
//            view.setOnClickListener(this) ;
//            //将该intent对象设置为View的tag属性 ， onClick时获取该tag ， --->getTag()
//            view.setTag(intent) ;
//
//            //将该View对象添加至LinearLayout中，由于大小发生了变化，系统会重新走”measure“ , ”layout“, ”draw“ 过程
//            //设置长宽高
//            LinearLayout.LayoutParams llparams = new LinearLayout.LayoutParams(80,90) ;
//            linearlayout.addView(view,llparams) ;
//        }
//        catch (PackageManager.NameNotFoundException e)
//        {
//            Log.e(TAG, "NameNotFoundException at completeAddApplication method") ;
//        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnDragListener) {
            mListener = (OnDragListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
//            mParam1 = getArguments().getString(ARG_PARAM1);
//            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        mContext = getActivity();
        EventBus.getDefault().register(this);
        mAdapterBottom = new BottomAdapter(mContext, mbotoms, this);
        iconSize = getResources().getDimensionPixelOffset(R.dimen.x35);
        float raio = getResources().getDimensionPixelOffset(R.dimen.x35) * 4f / ScreenUtils.getInstance().getScreenW();
        if (raio > 0.3f) {
            iconSize = ScreenUtils.getInstance().getScreenW() * 4 / 9 / 4;
        }
        appHeight = (iconSize + ScreenUtils.getInstance().sp2px(13) +
                ScreenUtils.getInstance().dp2px(5));


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_work_space, container, false);
        initView(rootView);
        getAppInfoList();
        setWorkPace();
        setBottomHotSeat();
        setSelectPage(1);

        new Handler().postDelayed(() -> {
            TopY = mViewPager.getTop();
            BottomY = mViewPager.getTop() + ((iconSize + ScreenUtils.getInstance().sp2px(13) +
                    ScreenUtils.getInstance().dp2px(5)) * miLinesNum +
                    ScreenUtils.getInstance().dp2px(20) * (miLinesNum - 1));
            iconSpace = (ScreenUtils.getInstance().getScreenW() / 4 - iconSize) / 2;


        }, 10);
        return rootView;
    }

    @Override
    public void onDestroy() {

        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public AppBean getDragBean() {
        return mDragBean;
    }

    private void setBottomHotSeat() {


        mGridViewBottom.setOnItemClickListener((adapterView, view, position, l) -> {

            //点击底部工具栏的中间键
            if (mbotoms.get(position).getActivityInfo() == null) {


            } else {
                float iconLeft = (position % 5 * (ScreenUtils.getInstance().getScreenW() / 5)) + view.findViewById(R.id.img_icon).getX();
                if (mGridViewBottom.downRawX < iconLeft || mGridViewBottom.downRawX > (iconLeft + view.findViewById(R.id.img_icon).getWidth())) {
                    return;
                }

                launchApp(-1, position);
            }

        });
        mGridViewBottom.setOnDragListener(new GragGridBottomView.OnDragListener() {
            @Override
            public void onDragApp(String pkgName) {
                mStrDragPkgName = pkgName;
                for (AppBean mbotom : mbotoms) {
                    if (mbotom.getActivityInfo() != null && TextUtils.equals(mStrDragPkgName, mbotom.getActivityInfo().packageName)) {
                        mDragBean = mbotom;
                        break;
                    }
                }

                mViewAdapters.get(mViewPager.getCurrentItem()).setDragBean(mDragBean);

            }

            @Override
            public void onDrag(@DragStatus int status) {
                mListener.onDrag(status);
                mViewPager.setPagingEnabled(status == DragStatus.Drag_end);
                mrlDelete.setVisibility(status == DragStatus.Drag_end ? View.GONE : View.VISIBLE);
                if (status == DragStatus.Drag_end) {

                    //还原一些默认配置
                    mViews.get(mViewPager.getCurrentItem()).resetViewOnDrag();
                    mGridViewBottom.resetViewOnDrag();
                    mAdapterBottom.setMbSetEmpty(false);
                    mViewAdapters.get(mViewPager.getCurrentItem()).setMbSetEmpty(false);

                    mAdapterBottom.setMbDragSetApp(false);
                    mViewAdapters.get(mViewPager.getCurrentItem()).setMbDragSetApp(false);


                    if (mtvDeleteBtn.isSelected()) {
                        Intent intent = null;
                        if (Tools.isHotSeat(mStrDragPkgName, null)) {
                            Toast.makeText(mContext, "系统应用禁止卸载", Toast.LENGTH_SHORT).show();
                            reSetLayout();
                            return;
                        }
                        //根据包名获取PackageInfo mPackageInfo;（需要处理异常）
                        PackageInfo mPackageInfo = null;
                        try {
                            mPackageInfo = mContext.getPackageManager().getPackageInfo(mStrDragPkgName, 0);
                            if ((mPackageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {
                                Toast.makeText(mContext, "系统应用禁止卸载", Toast.LENGTH_SHORT).show();
                                reSetLayout();
                                return;
                            }
                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();
                        }

                        intent = new Intent(Intent.ACTION_DELETE,
                                Uri.parse("package:" + mStrDragPkgName));
                        if (intent != null) startActivity(intent);
                    }
                    if (mtvAppInfo.isSelected()) {
                        Intent intent = new Intent();
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        if (Build.VERSION.SDK_INT >= 9) {
                            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                            intent.setData(Uri.fromParts("package", mStrDragPkgName, null));
                        } else if (Build.VERSION.SDK_INT <= 8) {
                            intent.setAction(Intent.ACTION_VIEW);
                            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                            intent.putExtra("com.android.settings.ApplicationPkgName", mStrDragPkgName);
                        }
                        if (intent != null) startActivity(intent);
                    }
                    reSetLayout();
                }

            }

            @Override
            public void onDragLocation(float eventX, float eventY) {

                isInDelete = (eventX > (ScreenUtils.getInstance().getScreenW() / 2 - mtvDeleteBtn.getWidth()) &&
                        eventX < (ScreenUtils.getInstance().getScreenW() / 2) &&
                        eventY > 0 && eventY < (mtvDeleteBtn.getHeight()));

                isInInfo = (eventX > ScreenUtils.getInstance().getScreenW() / 2 &&
                        eventX < (ScreenUtils.getInstance().getScreenW() / 2 + mtvAppInfo.getWidth()) &&
                        eventY > 0 && eventY < (mtvAppInfo.getHeight()));

                mtvDeleteBtn.setSelected(isInDelete);
                mtvAppInfo.setSelected(isInInfo);

                if (mtvDeleteBtn.isSelected()) {
                    mGridViewBottom.setAlphaBitmap(Color.argb(255, 254, 56, 57));
                } else if (mtvAppInfo.isSelected()) {
                    mGridViewBottom.setAlphaBitmap(Color.argb(255, 73, 130, 215));
                } else {
                    mGridViewBottom.setOriginalBitmap();

                }

            }

            @Override
            public void onDragEvent(MotionEvent ev) {

                if (ev.getAction() == MotionEvent.ACTION_MOVE) {
                    //move事件
                    mAdapterBottom.showHideView();
                    mAdapterBottom.setEmptyView();
                    mViews.get(miPageIndex).setDragImageView(mGridViewBottom.getDragImageView());
                    mViews.get(miPageIndex).setDragViewParams(mGridViewBottom.getDragViewParams());

                } else {
                    //up事件
                    //如果up时触摸位置在另一区域，但另一区域并没有插入数据，要求数据还原
                    boolean isSetOther = mAdapterBottom.isMbDragSetApp() || mViewAdapters.get(mViewPager.getCurrentItem()).isMbDragSetApp();
                    if (!isSetOther) {
                        mAdapterBottom.setRemoveDrag();
                        mAdapterBottom.showHideView();
                    }

                }
                mViews.get(miPageIndex).onTouchEvent(ev);
            }

            @Override
            public void onCancleDragEvent() {
                mViewAdapters.get(mViewPager.getCurrentItem()).setDragView();
                mViews.get(mViewPager.getCurrentItem()).resetViewOnDrag();
                mViews.get(mViewPager.getCurrentItem()).setIsViewOnDrag(false);
            }
        });
    }

    private void getAppInfoList() {
        DBUtil.getInstance(mContext).checkColumnExists();
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> mapps = mContext.getPackageManager().queryIntentActivities(intent, 0);
//            mapps.removeIf(app ->TextUtils.equals(app.activityInfo.packageName, getPackageName()));
        Iterator<ResolveInfo> it = mapps.iterator();
        List<AppBean> showApps = new ArrayList<>();
        mbotoms.clear();
        mappsAll.clear();
        while (it.hasNext()) {
            ResolveInfo a = it.next();
            LogUtil.e(TAG, "getAppInfoList==="+a.activityInfo.packageName );
            mappsAll.add(new AppBean.Builder()
                    .type(AppBean.AppType.LAUNCH_APP)
                    .name((String) a.loadLabel(mContext.getPackageManager()))
                    .activityInfo(a.activityInfo)
                    .pkgname(a.activityInfo.packageName)
                    .build());
            if (Tools.isHotSeat(a.activityInfo.packageName, mbotoms)) {
                if (mbotoms.size() < 4) {
                    mbotoms.add(new AppBean.Builder()
                            .type(AppBean.AppType.LAUNCH_APP)
                            .name((String) a.loadLabel(mContext.getPackageManager()))
                            .activityInfo(a.activityInfo)
                            .pkgname(a.activityInfo.packageName)
                            .build());
                }

                it.remove();
                continue;
            }

            if (TextUtils.equals(a.activityInfo.packageName, mContext.getPackageName())) {
                it.remove();
                continue;
            }

            showApps.add(new AppBean.Builder().
                    name((String) a.loadLabel(mContext.getPackageManager()))
                    .activityInfo(a.activityInfo)
                    .pkgname(a.activityInfo.packageName)
                    .build());
        }
        mbotoms.add(2, new AppBean.Builder().build());
        if (miLinesNum == 0) {
            getLine(1);
            miScreenNum = 4 * miLinesNum;
        }

        boolean isScreenOption = miScreenNum == DBUtil.getInstance(mContext).getNumOfScreen();

//        if (SharedPreferencesUtil.getScreenH(mContext) == ScreenUtils.getInstance().getScreenH() &&
//                SharedPreferencesUtil.getScreenW(mContext) == ScreenUtils.getInstance().getScreenW() &&
//                (mbotoms.size() - 1 + mapps.size()) == DBUtil.getInstance(mContext).getSizeApps()) {
        if (isScreenOption && (mbotoms.size() - 1 + mapps.size()) == DBUtil.getInstance(mContext).getSizeApps()) {
            List<List<AppBean>> appPages = DBUtil.getInstance(mContext).getApps();
            mShowApps.clear();
            for (List<AppBean> appPage : appPages) {
                List<AppBean> list = new ArrayList<>();
                for (AppBean appI : appPage) {

                    if (TextUtils.isEmpty(appI.getStrName())) {
                        list.add(appI);
                    } else {
                        if (TextUtils.isEmpty(appI.getIntent())) {
                            for (AppBean appBean : mappsAll) {
                                if (TextUtils.equals(appBean.getStrName(), appI.getStrName())) {
                                    appI.setActivityInfo(appBean.getActivityInfo());
                                    appI.setPkgName(appBean.getPkgName());
                                    list.add(appI);
                                    break;
                                }

                            }
                        } else {
                            for (AppBean appBean : mappsAll) {
                                if (TextUtils.equals(appBean.getStrName(), appI.getStrName().substring(0, appI.getStrName().indexOf("(")))) {
                                    appI.setActivityInfo(appBean.getActivityInfo());
                                    appI.setPkgName(appBean.getPkgName());
                                    list.add(appI);
                                }
                            }
                        }

                    }

                }
                mShowApps.add(list);
            }

            mbotoms.clear();
            List<AppBean> bottomApps = DBUtil.getInstance(mContext).getBottomApps();
            if (bottomApps.size() > 5) {
//                if ()
            }
            for (AppBean bottomApp : bottomApps) {
                if (TextUtils.isEmpty(bottomApp.getStrName())) {
                    mbotoms.add(bottomApp);
                } else {
                    if (TextUtils.isEmpty(bottomApp.getIntent())) {
                        for (AppBean appBean : mappsAll) {
                            if (TextUtils.equals(appBean.getStrName(), bottomApp.getStrName())) {
                                bottomApp.setActivityInfo(appBean.getActivityInfo());
                                bottomApp.setPkgName(appBean.getPkgName());
                                mbotoms.add(bottomApp);
                                break;
                            }

                        }
                    } else {
                        for (AppBean appBean : mappsAll) {
                            if (TextUtils.equals(appBean.getStrName(), bottomApp.getStrName().substring(0, bottomApp.getStrName().indexOf("(")))) {
                                bottomApp.setActivityInfo(appBean.getActivityInfo());
                                bottomApp.setPkgName(appBean.getPkgName());
                                mbotoms.add(bottomApp);
                            }
                        }
                    }


                }
            }


        } else {
            SharedPreferencesUtil.setScreenH(mContext, ScreenUtils.getInstance().getScreenH());
            SharedPreferencesUtil.setScreenW(mContext, ScreenUtils.getInstance().getScreenW());
            List<AppBean> list = new ArrayList<>();
            mShowApps.clear();
            for (ResolveInfo mapp : mapps) {
                if (list.size() < miScreenNum) {
                    list.add(new AppBean.Builder()
                            .type(AppBean.AppType.LAUNCH_APP)
                            .name((String) mapp.loadLabel(mContext.getPackageManager()))
                            .activityInfo(mapp.activityInfo)
                            .pkgname(mapp.activityInfo.packageName)
                            .build());
                    if (list.size() == miScreenNum) {
                        mShowApps.add(list);
                        list = new ArrayList<>();
                    }

                }
                if ((list.size() + mShowApps.size() * miScreenNum) == mapps.size() && list.size() != 0) {
                    List<AppBean> appShort = DBUtil.getInstance(mContext).getShortCut();
                    if (appShort != null && !appShort.isEmpty()) {
                        for (AppBean appBean : appShort) {
                            LogUtil.e(TAG, "getAppInfoList=======" + appBean.getStrName());
                            for (AppBean app : mappsAll) {
                                if (appBean.getStrName().indexOf("(")<0 || TextUtils.equals(appBean.getStrName().substring(0,
                                        appBean.getStrName().indexOf("(")),
                                        app.getStrName())) {
                                    appBean.setActivityInfo(app.getActivityInfo());
                                    appBean.setPkgName(app.getPkgName());
                                    appBean.setAppType(AppBean.AppType.LAUNCH_SHORT_CUT);
                                    list.add(appBean);
                                    break;
                                }

                            }
                        }
                    }
                    if (list.size() > miScreenNum) {
                        addLast(list.subList(miScreenNum, list.size()));

                    } else {
                        for (int i = list.size(); i < miScreenNum; i++) {
                            list.add(new AppBean.Builder().build());
                        }
                        mShowApps.add(list);
                    }

                }
            }
            if (mbotoms.size() != 5) {
                for (int i = mbotoms.size(); i < 5; i++) {
                    mbotoms.add(new AppBean.Builder().build());
                }
            }

            DBUtil.getInstance(mContext).deleteAllApps();
            DBUtil.getInstance(mContext).addAppsApp(mShowApps);
            DBUtil.getInstance(mContext).addBottomApp(mbotoms);
        }


        mllIndexs.removeAllViews();

        addIndexView();
    }


    private void addLast(List<AppBean> last) {
        if (last.size() > miScreenNum) {
            int max = (last.size() % miScreenNum == 0) ? (last.size() / miScreenNum) : (last.size() / miScreenNum + 1);
            for (int i = 0; i < (max); i++) {
                List<AppBean> appBeans = new ArrayList<>();
                for (int i1 = 0; i1 < miScreenNum; i1++) {
                    if ((i * miScreenNum + i1) >= last.size()) {
                        appBeans.add(new AppBean.Builder().build());

                    } else {

                        appBeans.add(last.get(i * miScreenNum + i1));
                    }

                }
                mShowApps.add(appBeans);
            }
        } else {
            List<AppBean> appBeans = new ArrayList<>();
            for (int i1 = 0; i1 < miScreenNum; i1++) {
                if ((i1) >= last.size()) {
                    appBeans.add(new AppBean.Builder().build());

                } else {

                    appBeans.add(last.get(i1));
                }

            }
            mShowApps.add(appBeans);
        }

    }

    /**
     * @param messageEvent 接收到安装或者卸载的信息
     *                     进行工作区的重新排列
     *                     <p>
     *                     mViewPager.getChildCount()的个数仅是可见的View的个数，并不代表所有个数
     */
    @Subscribe
    public void onEventMainThread(final AppEvent messageEvent) {
        int scroll = 0;
        if (messageEvent.getStatus() == 0) {
            //安装
            int[] indexArray = getFirstEmptyApp();

            AppBean appBean = null;
            if (TextUtils.isEmpty(messageEvent.getPackName())) {

            } else {
                Intent intent = new Intent(Intent.ACTION_MAIN, null);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                List<ResolveInfo> mapps = mContext.getPackageManager().queryIntentActivities(intent, 0);
//            mapps.removeIf(app ->TextUtils.equals(app.activityInfo.packageName, getPackageName()));
                Iterator<ResolveInfo> it = mapps.iterator();
                mappsAll.clear();
                while (it.hasNext()) {
                    ResolveInfo a = it.next();
                    mappsAll.add(new AppBean.Builder()
                            .type(AppBean.AppType.LAUNCH_APP)
                            .name((String) a.loadLabel(mContext.getPackageManager()))
                            .activityInfo(a.activityInfo)
                            .pkgname(a.activityInfo.packageName)
                            .build());
                }



                for (AppBean mapp : mappsAll) {
                    if (TextUtils.equals(mapp.getActivityInfo().packageName, messageEvent.getPackName())) {
                        appBean = mapp;
                        break;
                    }
                }

            }


            if (indexArray[0] == mShowApps.size()) {
                List<AppBean> list = new ArrayList<>();
                list.add(appBean);


                for (int i = 1; i < miScreenNum; i++) {
                    list.add(new AppBean.Builder().build());
                }
                mShowApps.add(list);
            } else {
                mShowApps.get(indexArray[0]).set(indexArray[1], appBean);
            }

            scroll = indexArray[0];
        } else {
            //卸载

            int[] indexArray = getAppIndex(messageEvent.getPackName());
            mShowApps.get(indexArray[0]).set(indexArray[1], new AppBean.Builder().build());
            scroll = indexArray[0];
            if (indexArray[0] == mShowApps.size() - 1 && getScreenAppNum(indexArray[0]) == 0) {
                mShowApps.remove(mShowApps.size() - 1);
                scroll -= 1;
            }

        }

        setWorkPace();
        mViewPager.setCurrentItem(scroll);
        setSelectPage(scroll + 1);

        mViewAdapters.get(scroll).notifyDataSetChanged();
        DBUtil.getInstance(mContext).deleteAppsApp();
        DBUtil.getInstance(mContext).addAppsApp(mShowApps);


    }

    public int[] getFirstEmptyApp() {
        int[] ints = new int[2];
        for (int i = 0; i < mShowApps.size(); i++) {
            for (int i1 = 0; i1 < mShowApps.get(i).size(); i1++) {
                if (mShowApps.get(i).get(i1)==null || mShowApps.get(i).get(i1).getActivityInfo() == null) {
                    ints[0] = i;
                    ints[1] = i1;

                    return ints;
                }
            }
        }
        ints[0] = mShowApps.size();
        ints[1] = 0;
        return ints;
    }

    /**
     * 获取包名代表的app所在的索引
     *
     * @param strPkgName 搜索的app包名
     * @return 页面索引与app索引
     */
    public int[] getAppIndex(String strPkgName) {
        int[] ints = new int[2];
        for (int i = 0; i < mShowApps.size(); i++) {
            for (int i1 = 0; i1 < mShowApps.get(i).size(); i1++) {
                if (TextUtils.equals(mShowApps.get(i).get(i1).getActivityInfo().packageName, strPkgName)) {
                    ints[0] = i;
                    ints[1] = i1;

                    return ints;
                }
            }
        }
        ints[0] = mShowApps.size();
        ints[1] = 0;
        return ints;
    }

    /**
     * 获取某一页的非空app的数量
     *
     * @param miPageIndex 页面索引
     * @return app数量
     */
    private int getScreenAppNum(int miPageIndex) {
        int size = 0;
        for (AppBean appBean : mShowApps.get(miPageIndex)) {
            if (appBean.getActivityInfo() != null) {
                size += 1;
            }
        }
        return size;

    }

    private void setWorkPace() {
        mViews.clear();
        mViewAdapters.clear();
        for (int i = 0; i < mShowApps.size(); i++) {
            mViews.add(addGridView((ArrayList<AppBean>) mShowApps.get(i)));
        }
        myPagerAdapter = new WorkSpacePagerAdapter(mViews);

        mViewPager.setAdapter(myPagerAdapter);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                miPageIndex = position;
                setSelectPage(miPageIndex + 1);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 设置滑动页面时的圆点缩放动画
     *
     * @param selectPage
     */
    private void setSelectPage(int selectPage) {
        if (mllIndexs.getChildCount() > selectPage) {
            for (int i = 0; i < mDianImages.length; i++) {
                if (i == selectPage) {
                    AnimUtil.ValueAnimatorHeighAndWidth(mDianImages[i], true, true, (int) getResources().getDimension(R.dimen.x8), (int) getResources().getDimension(R.dimen.x10), 100);
                } else {
                    if (mDianImages[i].getHeight() > ((int) getResources().getDimension(R.dimen.x8))) {
                        AnimUtil.ValueAnimatorHeighAndWidth(mDianImages[i], true, true, (int) getResources().getDimension(R.dimen.x10), (int) getResources().getDimension(R.dimen.x8), 100);
                    }
                }
            }
        }
    }

    private GragGridView addGridView(ArrayList<AppBean> appBeans) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.MATCH_PARENT);
        GragGridView gridView = new GragGridView(mContext);
//        gridView.setPadding(ScreenUtils.getInstance().dp2px(30), 0, ScreenUtils.getInstance().dp2px(30), 0);
        gridView.setNumColumns(4);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridView.setOnDragListener(this);

        gridView.setVerticalSpacing(ScreenUtils.getInstance().dp2px(20));
        gridView.setLayoutParams(params);
        GridViewAdapter adapter = new GridViewAdapter(mContext, appBeans, miScreenNum, this);
        gridView.setAdapter(adapter);
        mViewAdapters.add(adapter);
        gridView.setOnItemClickListener((adapterView, view, position, l) -> {
            if (appBeans.get(position).getActivityInfo() != null) {
                float iconLeft = (position % 4 * (ScreenUtils.getInstance().getScreenW() / 4)) + view.findViewById(R.id.img_icon).getX();

                //根据触摸点的X位置，判断是否点击的是item的空位置
                if (gridView.downRawX < iconLeft || gridView.downRawX > (iconLeft + view.findViewById(R.id.img_icon).getWidth())) {
                    return;
                }


                launchApp(miPageIndex, position);
            }
        });
        return gridView;

    }

    /**
     * 启动app
     *
     * @param index_page 页面的索引
     * @param index_app  当前页面的app索引
     */
    private void launchApp(int index_page, int index_app) {
        Intent intent = new Intent();
        //如果不加flag，跳转的app还在同一个栈
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (index_page < 0) {

            if (mbotoms.get(index_app).getAppType() == AppBean.AppType.LAUNCH_APP) {

                intent.setComponent(new ComponentName(
                        mbotoms.get(index_app).getActivityInfo().packageName,
                        mbotoms.get(index_app).getActivityInfo().name));
            } else {
                try {
                    intent = Intent.parseUri(mbotoms.get(index_app).getIntent(), 0);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }

        } else {
            if (mShowApps.get(index_page).get(index_app).getAppType() == AppBean.AppType.LAUNCH_APP) {


                LogUtil.e(TAG, "launchApp: "+ mShowApps.get(index_page).get(index_app).getActivityInfo().packageName+"=="+
                        mShowApps.get(index_page).get(index_app).getActivityInfo().name);
                intent.setComponent(new ComponentName(
                        mShowApps.get(index_page).get(index_app).getActivityInfo().packageName,
                        mShowApps.get(index_page).get(index_app).getActivityInfo().name));

            } else {
                try {
                    intent = Intent.parseUri(mShowApps.get(index_page).get(index_app).getIntent(), 0);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
        }

        startActivity(intent);
    }

    /**
     * @param messageEvent 接收到快捷方式的通知
     *                     <p>
     *                     mViewPager.getChildCount()的个数仅是可见的View的个数，并不代表所有个数
     */
    @Subscribe
    public void onEventMainThread(final ShortCutEvent messageEvent) {
        int scroll = 0;
        if (messageEvent.getStatus() == 0) {
            //安装
            List<Integer> indexArray = messageEvent.getIndexArr();

            AppBean appI = messageEvent.getAppBean();
            for (AppBean appBean : mappsAll) {
                if (TextUtils.equals(appBean.getStrName(), appI.getStrName().substring(0, appI.getStrName().indexOf("(")))) {
                    appI.setActivityInfo(appBean.getActivityInfo());
                    appI.setPkgName(appBean.getPkgName());
                    break;
                }
            }
            mShowApps.get(indexArray.get(0)).set(indexArray.get(1), appI);

            mViewAdapters.get(indexArray.get(0)).notifyDataSetChanged();
        }

    }

    /**
     * 使用递归找出最合适的界面图标行数
     *
     * @param line
     */
    private void getLine(int line) {
        int space = (int) (ScreenUtils.getInstance().getScreenH() -
                ScreenUtils.getInstance().dp2px(60 + 20 + 20 + 10 + 5) -
                iconSize -
                getResources().getDimensionPixelSize(ScreenUtils.getInstance().getStatusBarHeight())
                - ScreenUtils.getInstance().sp2px(13));


        int height = (int) ((iconSize + ScreenUtils.getInstance().sp2px(13) +
                ScreenUtils.getInstance().dp2px(5)) * line +
                ScreenUtils.getInstance().dp2px(20) * (line - 1));


        if (height > space) {
            miLinesNum += (line - 1);
        } else {
            line += 1;
            getLine(line);
        }
    }



    private void initView(View rootView) {
        mrlContent = rootView.findViewById(R.id.rl_content);
        mllIndexs = rootView.findViewById(R.id.ll_index);
        mGridViewBottom = rootView.findViewById(R.id.grid_bottom);
        mGridViewBottom.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mViewPager = rootView.findViewById(R.id.viewPager);


        mrlDelete = rootView.findViewById(R.id.rl_deleteApp);
        mtvDeleteBtn = rootView.findViewById(R.id.text_delete);
        mtvAppInfo = rootView.findViewById(R.id.text_appInfo);
        mGridViewBottom.setAdapter(mAdapterBottom);
    }

    /**
     * 拖拽的app
     *
     * @param pkgName 包名packageName
     */
    @Override
    public void onDragApp(String pkgName) {
        mStrDragPkgName = pkgName;
        for (AppBean mbotom : mShowApps.get(mViewPager.getCurrentItem())) {
            if (mbotom.getActivityInfo() != null && TextUtils.equals(mStrDragPkgName, mbotom.getActivityInfo().packageName)) {
                mDragBean = mbotom;
                break;
            }
        }
        mAdapterBottom.setDragBean(mDragBean);
    }

    /**
     * 拖拽状态改变监听
     *
     * @param status 开始和结束
     */
    @Override
    public void onDrag(@DragStatus int status) {
        mListener.onDrag(status);
        mViewPager.setPagingEnabled(status == DragStatus.Drag_end);
        mrlDelete.setVisibility(status == DragStatus.Drag_end ? View.GONE : View.VISIBLE);
        if (status == DragStatus.Drag_end) {
            if (mbToNext) {
                if (mbIsToNext) {
                    mViewAdapters.get(miPageIndex - 1).showHideView();
                    mViewAdapters.get(miPageIndex - 1).setEmptyView();
                    mViewAdapters.get(miPageIndex - 1).setMbSetEmpty(false);
                } else {

                    mViewAdapters.get(miPageIndex + 1).showHideView();
                    mViewAdapters.get(miPageIndex + 1).setEmptyView();
                    mViewAdapters.get(miPageIndex + 1).setMbSetEmpty(false);

                }

            }

            mGridViewBottom.resetViewOnDrag();
            mViews.get(miPageIndex).resetViewOnDrag();
            mAdapterBottom.setMbSetEmpty(false);
            mViewAdapters.get(miPageIndex).setMbSetEmpty(false);

            mAdapterBottom.setMbDragSetApp(false);
            mViewAdapters.get(miPageIndex).setMbDragSetApp(false);


            mViews.get(miPageIndex).setIsViewOnDrag(false);

            mbToNext = false;
            //拖拽app  ViewPager横向滑动换屏后


            if (mtvDeleteBtn.isSelected()) {
                Intent intent = null;
                if (Tools.isHotSeat(mStrDragPkgName, null)) {
                    Toast.makeText(mContext, "系统应用禁止卸载", Toast.LENGTH_SHORT).show();
                    reSetLayout();
                    return;
                }
                //根据包名获取PackageInfo mPackageInfo;（需要处理异常）
                PackageInfo mPackageInfo = null;
                try {
                    mPackageInfo = mContext.getPackageManager().getPackageInfo(mStrDragPkgName, 0);
                    if ((mPackageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {
                        Toast.makeText(mContext, "系统应用禁止卸载", Toast.LENGTH_SHORT).show();
                        reSetLayout();
                        return;
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }

                if (mDragBean.getAppType() == AppBean.AppType.LAUNCH_SHORT_CUT) {
                    //我的多开app建立的桌面快捷方式的话，只删除集合中的数据，并修改数据库就行，

                    mShowApps.get(miPageIndex).set(mViewAdapters.get(miPageIndex).getDragIndex(), new AppBean.Builder().build());
                    int[] indexArr=  new int[2];
                    indexArr[0]=miPageIndex;
                    indexArr[1]=mViewAdapters.get(miPageIndex).getDragIndex();

                    DBUtil.getInstance(mContext).setAppsApp(indexArr,new AppBean.Builder().build());
                    //


                    mViewAdapters.get(miPageIndex).notifyDataSetChanged();
                } else {
                    intent = new Intent(Intent.ACTION_DELETE,
                            Uri.parse("package:" + mStrDragPkgName));
                    if (intent != null) startActivity(intent);

                }

            }
            if (mtvAppInfo.isSelected()) {
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT >= 9) {
                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    intent.setData(Uri.fromParts("package", mStrDragPkgName, null));
                } else if (Build.VERSION.SDK_INT <= 8) {
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                    intent.putExtra("com.android.settings.ApplicationPkgName", mStrDragPkgName);
                }
                if (intent != null) startActivity(intent);
            }
            reSetLayout();
        }

    }

    private void reSetLayout() {
        if (mtvDeleteBtn.isSelected()) mtvDeleteBtn.setSelected(false);
        if (mtvAppInfo.isSelected()) mtvAppInfo.setSelected(false);
        mViews.get(mViewPager.getCurrentItem()).setOriginalBitmap();
    }

    @Override
    public void onDragLocation(float eventX, float eventY) {
        if (eventY <= mtvDeleteBtn.getHeight()) {

            isInDelete = (eventX > (ScreenUtils.getInstance().getScreenW() / 2 - mtvDeleteBtn.getWidth()) && eventX < (ScreenUtils.getInstance().getScreenW() / 2) &&
                    eventY > 0 && eventY < (mtvDeleteBtn.getHeight()));

            isInInfo = (eventX > ScreenUtils.getInstance().getScreenW() / 2 && eventX < (ScreenUtils.getInstance().getScreenW() / 2 + mtvAppInfo.getWidth()) &&
                    eventY > 0 && eventY < (mtvAppInfo.getHeight()));

            mtvDeleteBtn.setSelected(isInDelete);
            mtvAppInfo.setSelected(isInInfo);

            if (mtvDeleteBtn.isSelected()) {
                mViews.get(mViewPager.getCurrentItem()).setAlphaBitmap(Color.argb(255, 254, 56, 57));
            } else if (mtvAppInfo.isSelected()) {
                mViews.get(mViewPager.getCurrentItem()).setAlphaBitmap(Color.argb(255, 73, 130, 215));
            } else {
                mViews.get(mViewPager.getCurrentItem()).setOriginalBitmap();

            }
        } else {
            reSetLayout();

        }

    }

    /**
     * 拖拽到其他区域的事件
     *
     * @param ev 触摸事件
     */
    @Override
    public void onDragEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            mViewAdapters.get(mViewPager.getCurrentItem()).showHideView();
            Log.e("getAction", "move----------------------------2");
            mViewAdapters.get(mViewPager.getCurrentItem()).setEmptyView();
            mGridViewBottom.setDragImageView(mViews.get(mViewPager.getCurrentItem()).getDragImageView());
            mGridViewBottom.setDragViewParams(mViews.get(mViewPager.getCurrentItem()).getDragViewParams());
        } else {
            //如果up时触摸位置在另一区域，但另一区域并没有插入数据，要求数据还原
            boolean isSetOther = mAdapterBottom.isMbDragSetApp() || mViewAdapters.get(mViewPager.getCurrentItem()).isMbDragSetApp();
            if (!isSetOther) {
                mViewAdapters.get(mViewPager.getCurrentItem()).setRemoveDrag();
                mViewAdapters.get(mViewPager.getCurrentItem()).showHideView();
            }


        }
        mGridViewBottom.onTouchEvent(ev);
    }

    /**
     * 拖拽到下一页或上一页的分发事件
     *
     * @param ev     触摸事件
     * @param isNext 是否是前往下一页
     */
    @Override
    public void onDragNextEvent(MotionEvent ev, boolean isNext) {


        mbIsToNext = isNext;
        if (!mbToNext) {

            mbToNext = true;
            if (isNext) {
                LogUtil.e(TAG, "onDragNextEvent===" + (miPageIndex + 1));
                if (miPageIndex + 1 >= mViews.size()) {
                    List<AppBean> list = new ArrayList<>();
                    for (int i = 0; i < miScreenNum; i++) {
                        list.add(new AppBean.Builder().build());
                    }

                    mShowApps.add(list);
                    mViews.add(addGridView((ArrayList<AppBean>) mShowApps.get(mShowApps.size() - 1)));
                    myPagerAdapter.notifyDataSetChanged();
                    addIndexView();

//                return;
                }
            } else {
                if (miPageIndex - 1 < 0) {
                    return;
                }
            }

            mViewAdapters.get(miPageIndex).showHideView();
            mViewAdapters.get(miPageIndex).setEmptyView();
            mViews.get(miPageIndex).resetViewOnDrag();
            Log.e("getAction", "move----------------------------2" + miPageIndex);
            mViews.get(mbIsToNext ? (miPageIndex + 1) : (miPageIndex - 1)).setDragImageView(mViews.get(miPageIndex).getDragImageView());
            mViews.get(mbIsToNext ? (miPageIndex + 1) : (miPageIndex - 1)).setDragViewParams(mViews.get(miPageIndex).getDragViewParams());
            mViewAdapters.get(mbIsToNext ? (miPageIndex + 1) : (miPageIndex - 1)).setDragBean(mDragBean);
            mViewPager.setCurrentItem(mbIsToNext ? (miPageIndex + 1) : (miPageIndex - 1));
        }
//        mViews.get(miPageIndex).onTouchEvent(ev);

    }

    /**
     * 生成指示圆点，并加入到 LinearLayout 中去
     */
    private void addIndexView() {
        mDianImages = new ImageView[mShowApps.size() + 1];
        mllIndexs.removeAllViews();
        for (int i = 0; i < mShowApps.size() + 1; i++) {
            ImageView ivdian = new ImageView(mContext);
            if (i == 0) {
                ivdian.setImageResource(R.mipmap.icon_search);
            } else {
                ivdian.setImageResource(R.drawable.shape_index);

            }
            ivdian.setScaleType(ImageView.ScaleType.FIT_XY);
            LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams((int) getResources().getDimension(R.dimen.x8), (int) getResources().getDimension(R.dimen.x8));
            params3.setMargins(getResources().getDimensionPixelSize(R.dimen.x5), 0, getResources().getDimensionPixelSize(R.dimen.x5), 0);
            ivdian.setLayoutParams(params3);

            mllIndexs.addView(ivdian);
            mDianImages[i] = ivdian;
            int finalI = i;
            mDianImages[i].setOnClickListener(view -> {
                if (finalI == 0) {
                    if (mListener != null) {
                        mListener.onToSearch();
                    }
                } else {
                    mViewPager.setCurrentItem(finalI - 1, true);
                }
            });
        }
    }

    @Override
    public void onCancleDragEvent() {
        mAdapterBottom.setDragView();
        mGridViewBottom.resetViewOnDrag();
        mGridViewBottom.setIsViewOnDrag(false);
    }

    @Override
    public void onCancleDragNextEvent() {

        int index = mbIsToNext ? miPageIndex - 1 : miPageIndex + 1;
        // 还原
//        LogUtil.e(TAG, "onCancleDragNextEvent==="+index+"="+
//                mViewAdapters.get(index).getAppDrag().getStrName()+"=="+
//                mViewAdapters.get(index).getDragIndex()
//
//        );
//        mShowApps.get(index).set(mViewAdapters.get(mbIsToNext?miPageIndex-1:miPageIndex+1).getDragIndex(),mDragBean);
        mViewAdapters.get(index).setRemoveDrag();
        mViewAdapters.get(index).showHideView();

        //防止up操作出发其他赋值操作
        mViewAdapters.get(index).setMdragIndex(-1);


    }

    @Override
    public void setLastApp(AppBean app) {
        miInsertIndex = mViewPager.getCurrentItem();
        setAppData(mViewPager.getCurrentItem() + 1, app);
    }

    @Override
    public void onChangeApps() {
        LogUtil.e(TAG, "onChangeApps===" + mViewAdapters.get(0).getMapps().size() + "==" + mViewAdapters.get(1).getMapps().size());
        DBUtil.getInstance(mContext).deleteAppsApp();
        DBUtil.getInstance(mContext).addAppsApp(mShowApps);
    }

    @Override
    public void onChangeBottomApps() {
        LogUtil.e(TAG, "onChangeApps===bottom==" + mViewAdapters.get(0).getMapps().size() + "==" + mViewAdapters.get(1).getMapps().size());

        DBUtil.getInstance(mContext).deleteBottomApps();
        if (mbotoms.size() > 5) {
            LogUtil.e(TAG, "onChangeBottomApps====" + mbotoms.size());
        }
        DBUtil.getInstance(mContext).addBottomApp(mbotoms);
    }

    /**
     * 需考虑所有屏幕都是满数据，只能add最后一个屏幕并放入
     *
     * @param miPageIndex
     * @param app
     */
    private void setAppData(int miPageIndex, AppBean app) {
        if (miPageIndex >= mShowApps.size()) {

            List<AppBean> list = new ArrayList<>();
            list.add(app);
            for (int i = 1; i < miScreenNum; i++) {
                list.add(new AppBean.Builder().build());
            }
            mShowApps.add(list);

            setWorkPace();
            mViewPager.setCurrentItem(miInsertIndex);

        } else {
            if (getScreenAppNum(miPageIndex) >= miScreenNum) {
                miPageIndex += 1;
                setAppData(miPageIndex, app);
            } else {
                mShowApps.get(miPageIndex).add(0, app);
                mShowApps.get(miPageIndex).remove(getScreenEmptyAppIndex(miPageIndex));
                mViewAdapters.get(miPageIndex).notifyDataSetChanged();
            }

        }

    }

    /**
     * 获取某一页的空app的索引
     *
     * @param miPageIndex
     * @return
     */
    private int getScreenEmptyAppIndex(int miPageIndex) {
        int select = 0;
        for (int i = 0; i < mShowApps.get(miPageIndex).size(); i++) {
            if (mShowApps.get(miPageIndex).get(i).getActivityInfo() == null) {
                select = i;
                break;
            }
        }
        return select;

    }


    /**
     * 回调给MainActivity的接口
     */
    public interface OnDragListener {
        void onDrag(@DragStatus int status);

        void onToSearch();
    }
}
